package com.weibo.survey.service.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.weibo.survey.dao.BaseDao;
import com.weibo.survey.domain.Page;
import com.weibo.survey.domain.Survey;
import com.weibo.survey.domain.User;
import com.weibo.survey.service.SurveyService;
import com.weibo.survey.utils.ValidateUtils;

@Service("surveyService")
public class SurveyServiceImpl extends BaseServiceImpl<Survey> implements SurveyService {
	@Resource(name = "surveyDao")
	public void setBaseDao(BaseDao<Survey> baseDao) {
		super.setBaseDao(baseDao);
	}

	@Override
	public Survey newSurvey(User user) {
		Survey survey = new Survey();
		survey.setUser(user);
		Page page = new Page();
		page.setSurvey(survey);
		survey.getPages().add(page);
		saveEntity(survey);
		return survey;
	}

	@Override
	public List<Survey> findAllSurvey(User user) {
		return baseDao.getEntitiesByHql("from Survey s where s.user.id=?", user.getId());
	}

	@Override
	public Survey getSurveyWithChildren(int id) {
		Survey survey = getEntity(id);
		Set<Page> pages = survey.getPages();
		if (ValidateUtils.isValidate(pages)) {
			for (Page page : pages) {
				page.getQuestions().size();
			}
		}
		return survey;
	}

	@Override
	public void deleteSurvey(int id) {
		// 1.删除答案
		String hql = "delete from Answer a where a.surveyId=?";
		batchByHql(hql, id);
		// 2.删除问题
		hql = "delete from Question q where q.page.id in (select p.id from Page p where p.survey.id=?)";
		batchByHql(hql, id);
		// 3.删除页面
		hql = "delete from Page p where p.survey.id=?";
		batchByHql(hql, id);
		// 4.删除调查
		hql = "delete from Survey s where s.id=?";
		batchByHql(hql, id);
	}

	@Override
	public void clearSurvey(int id) {
		String hql = "delete from Answer a where a.surveyId=?";
		baseDao.batchByHql(hql, id);
	}

	@Override
	public void toggleSurvey(int id) {
		Survey survey = getEntity(id);
		if (survey != null) {
			String hql = "update Survey s set s.closed=? where s.id=?";
			batchByHql(hql, !survey.isClosed(), id);
		}
	}

	@Override
	public void updateLogoPhoto(int id, String logoPhoto) {
		String hql = "update Survey s set s.logoPhoto=? where s.id=?";
		batchByHql(hql, logoPhoto, id);
	}
}
